package cn.dankal.flyaudio.store;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.ShopUserServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.ApplyAfterSalesEntity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.CreateOrderPreviewEntity;
import cn.dankal.basiclib.pojo.InputLogiReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.CallPhoneUtil;
import cn.dankal.basiclib.util.SpannableStringUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ProductsAdapter;
import cn.dankal.flyaudio.personal.MyOrderActivity;
import cn.dankal.flyaudio.personal.NegotiationHistoryActivity;
import cn.dankal.flyaudio.pop.AfterSalesOrderInputPop;
import cn.dankal.flyaudio.pop.AfterSalesPop;

public class RefundDetailActivity extends BaseActivity implements View.OnClickListener {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_refund_detail;
    }

    ConstraintLayout clOrder, clShou, clOrderExpress, clStatus;
    private CreateOrderPreviewEntity orderDetail;
    private String orderUuid = "";
    private RecyclerView recyclerview;
    private ProductsAdapter adapter;

    private RelativeLayout rlSuccessPrice;
    private ImageView ivOrderState;
    private TextView tvShouName, tvAddress, tvNumber,
            tvPrompt2, tvConfirmEdit, tvRevokeEdit,
            tvOrderState, tvStatusText, tvPrompt1,
            tvCreatedDatetime, tvNeedPay, tvUserReason, tvUuid, tvPrice, getTvRevokeEdit,
            tvRevoke, tvUpdate, tvOrderNum, tvOrderTypeNum,
            tvRevoke1;

    @Override
    protected void initComponents() {
        addSingleTitleBar("售后详情");

        orderUuid = getIntent().getStringExtra("orderUuid");
        clOrder = findViewById(R.id.cl_order);
        clOrder.setOnClickListener(this);
        recyclerview = findViewById(R.id.mRv);
        adapter = new ProductsAdapter();
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setAdapter(adapter);
//        adapter.setOnRvItemClickListener(new OnRvItemClickListener<ProductDetailItemEntity>() {
//            @Override
//            public void onItemClick(View v, int position, ProductDetailItemEntity data) {
//                Intent intent = new Intent(ActivityUtils.getTopActivity(), MyOrderDetailActivity.class);
//                intent.putExtra("orderUuid", orderUuid);
//                ActivityUtils.getTopActivity().startActivity(intent);
//            }
//        });
        RelativeLayout rl_negotiation = findViewById(R.id.rl_negotiation);
        tvOrderState = findViewById(R.id.tv_order_state);
        tvShouName = findViewById(R.id.tv_shou_name);
        tvAddress = findViewById(R.id.tv_address);
        tvNumber = findViewById(R.id.tv_number);
        tvPrompt2 = findViewById(R.id.tv_prompt_2);
        tvConfirmEdit = findViewById(R.id.tv_confirm_edit);
        tvRevokeEdit = findViewById(R.id.tv_revoke_edit);
        clShou = findViewById(R.id.cl_shou);
        tvStatusText = findViewById(R.id.tv_status_text);
        tvPrompt1 = findViewById(R.id.tv_prompt_1);
        tvCreatedDatetime = findViewById(R.id.tv_createdDatetime);
        tvNeedPay = findViewById(R.id.tv_needPay);
        tvUserReason = findViewById(R.id.tv_userReason);
        tvUuid = findViewById(R.id.tv_uuid);
        tvRevoke = findViewById(R.id.tv_revoke);
        tvPrice = findViewById(R.id.tv_price);
        tvUpdate = findViewById(R.id.tv_update);
        clOrderExpress = findViewById(R.id.cl_order_express);
        tvOrderNum = findViewById(R.id.tv_order_num);
        tvOrderTypeNum = findViewById(R.id.tv_order_type_num);
        tvRevoke1 = findViewById(R.id.tv_revoke_1);
        ivOrderState = findViewById(R.id.iv_order_state);
        rlSuccessPrice = findViewById(R.id.rl_success_price);
        clStatus = findViewById(R.id.cl_status);
        tvRevoke1.setOnClickListener(this);
        rl_negotiation.setOnClickListener(this);
        tvUpdate.setOnClickListener(this);
        tvConfirmEdit.setOnClickListener(this);
        tvRevokeEdit.setOnClickListener(this);
        tvRevoke.setOnClickListener(this);
        getOrderDetail();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_update:
                //修改申请
                if (TextUtils.equals(orderDetail.getAfterSaleApply().getState(), MyOrderActivity.REJECTED)) {

                    //联系客服
                    SelectDialog.show(this, "是否需要拨打",
                            "400-9200-108", "是", (dialog2, which) -> {
                                CallPhoneUtil.callPhoneAndPermission(RefundDetailActivity.this, "400-9200-108");
                            }, "否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                } else {
                    new AfterSalesPop(this).setDoApplyListener(new AfterSalesPop.DoApplyListener() {
                        @Override
                        public void doApply(String reason, boolean isRefundOnlyMoney) {
                            ApplyAfterSalesEntity req = new ApplyAfterSalesEntity();
                            req.setUserReason(reason);
                            if (isRefundOnlyMoney) {
                                req.setType("RETURN_MONEY_ONLY");
                            } else {
                                req.setType("RETURN_MONEY_PRODUCT");
                            }
                            req.setOrderUuid(orderUuid);
                            ShopUserServiceFactory.applySales(req).subscribe(new AbstractSubscriber<BaseResponse<Object>>(RefundDetailActivity.this) {
                                @Override
                                public void onNext(BaseResponse<Object> objectBaseResponse) {
                                    getOrderDetail();
                                }
                            });
                        }
                    }).setPopupGravity(Gravity.CENTER).showPopupWindow(findViewById(android.R.id.content));
                }
                break;
            case R.id.tv_revoke_1:
                showDeleteDialog();
                break;
            case R.id.tv_revoke:
                showDeleteDialog();
                break;
            case R.id.tv_revoke_edit:
                //撤销申请
                showDeleteDialog();
                break;
            case R.id.tv_confirm_edit:
                //点击填写物流单号
                new AfterSalesOrderInputPop(this).setDoApplyListener(new AfterSalesOrderInputPop.DoInputOrderNumListener() {
                    @Override
                    public void doApply(String reason, String orderNum) {
                        InputLogiReq rq = new InputLogiReq();
                        rq.setUuid(orderDetail.getAfterSaleApply().getUuid());
                        rq.setExpressNum(orderNum);
                        rq.setExpressCorpCode(reason);
                        ShopUserServiceFactory.shipment(rq).subscribe(new AbstractSubscriber<BaseResponse<Object>>(RefundDetailActivity.this) {
                            @Override
                            public void onNext(BaseResponse<Object> objectBaseResponse) {
                                LiveEventBus.get("refresh_refund_order", String.class).post("");
                                getOrderDetail();
                            }
                        });
                    }
                }).setPopupGravity(Gravity.CENTER).showPopupWindow(findViewById(android.R.id.content));
                break;
            case R.id.cl_order:
                Bundle bundle1 = new Bundle();
                bundle1.putString("orderUuid", orderUuid);
                bundle1.putString("number",
                        orderDetail.getAfterSaleApply().getExpressCorpCode());
                bundle1.putString("orderType", orderDetail.getAfterSaleApply().getExpressCorpName());
                bundle1.putString("type", "2");
                ActivityUtils.startActivity(bundle1, LogisticsActivity.class);
                break;

            case R.id.rl_negotiation:
                Bundle bundle = new Bundle();
                bundle.putSerializable("model", orderDetail);
                ActivityUtils.startActivity(bundle, NegotiationHistoryActivity.class);
                break;

        }
    }

    private void showDeleteDialog() {
        //撤销申请
        SelectDialog.show(this, "提示",
                "是否撤销申请", "是", (dialog2, which) -> {
                    deleteOrder();
                }, "否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
    }

    private void deleteOrder() {
        showLoadingDialog();
        String afterUuid = orderDetail.getAfterSaleApply().getUuid();
        ShopUserServiceFactory.deleteSales(afterUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
                    @Override
                    public void onNext(BaseResponse<Object> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("撤销成功");
                        LiveEventBus.get("refresh_refund_order", String.class).post("");
                        finishActivity();
                    }
                });
    }

    /**
     * 获取订单详情
     */
    private void getOrderDetail() {
        showLoadingDialog();
        ShopUserServiceFactory.getOrderDetails(orderUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<CreateOrderPreviewEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<CreateOrderPreviewEntity> createOrderPreviewEntityBaseResponse) {
                        dismissLoadingDialog();
                        CreateOrderPreviewEntity data = createOrderPreviewEntityBaseResponse.getData();
                        orderDetail = data;
                        adapter.addDatas(orderDetail.getOrderItemList(), true);
                        tvCreatedDatetime.setText("申请时间：" + orderDetail.getCreatedDatetime());
                        tvNeedPay.setText("退款金额：￥" + orderDetail.getNeedPay());
                        tvPrice.setText("¥" + orderDetail.getNeedPay());
                        if (orderDetail.getAfterSaleApply() != null) {
                            tvUserReason.setText("退款原因：" + orderDetail.getAfterSaleApply().getUserReason());
                            tvUuid.setText("退款编号：" + orderDetail.getAfterSaleApply().getUuid());
                            String state = data.getAfterSaleApply().getState();
                            if (TextUtils.equals(state, MyOrderActivity.WAITING_SHIP)) {
                                showWaitingShip();
                            } else if (TextUtils.equals(state, MyOrderActivity.WAITING)) {
                                showWaiting();
                            } else if (TextUtils.equals(state, MyOrderActivity.WAITING_REFUND) || TextUtils.equals(state, MyOrderActivity.SHIPPING)) {
                                waittingRefund();
                            } else if (TextUtils.equals(state, MyOrderActivity.REJECTED)) {
                                rejected();
                            } else if (TextUtils.equals(state, MyOrderActivity.REFUND_SUCCESS)) {
                                success();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        finish();
                    }
                });
    }

    private void success() {

        ivOrderState.setVisibility(View.VISIBLE);
        ivOrderState.setImageResource(R.mipmap.icon_jiaoyuwancheng);
        tvOrderState.setText("退款成功");
        if (TextUtils.equals(orderDetail.getAfterSaleApply().getType(), "RETURN_MONEY_PRODUCT")) {
            clStatus.setVisibility(View.GONE);
        } else {
            clStatus.setVisibility(View.VISIBLE);
            tvStatusText.setText("您的退款申请审核通过");
            tvPrompt1.setText("· 您的退款申请已成功\n· 请等待商家退款返回您的账户");
        }

        rlSuccessPrice.setVisibility(View.VISIBLE);
    }

    private void waittingRefund() {
        //等待商家收货并退款
        tvOrderState.setText("等待商家收货并退款");
        tvStatusText.setText("如果商家收到货并验货无误，将操作退款给您");
        clOrderExpress.setVisibility(View.VISIBLE);
        tvConfirmEdit.setVisibility(View.GONE);
        tvOrderNum.setText("订单编号：" + orderDetail.getUuid());
        tvOrderTypeNum.setText(orderDetail.getAfterSaleApply().getExpressCorpName());
        tvRevoke1.setVisibility(View.VISIBLE);
    }

    private void rejected() {
        ivOrderState.setVisibility(View.VISIBLE);
        ivOrderState.setImageResource(R.mipmap.icon_jiaoyiguanbi);
        tvOrderState.setText("退款关闭");
        tvStatusText.setText("您的退款申请审核不通过，退款已关闭。");
        tvPrompt1.setText("· 如果商家拒绝，您的订单未得到处理，请联系商家协商处理");
        tvUpdate.setText("联系客服");
        tvPrompt1.setVisibility(View.VISIBLE);
        tvUpdate.setVisibility(View.VISIBLE);

    }

    //商家已同意退货申请，请尽早退货。
    private void showWaitingShip() {
        clShou.setVisibility(View.VISIBLE);
        tvOrderState.setText("请尽早退货给商家");
        tvStatusText.setText("商家已同意退货申请，请尽早退货。");
        if (orderDetail.getUserAddress() != null) {
            tvShouName.setText("收货人：" + orderDetail.getUserAddress().getContacter());
            tvNumber.setText(orderDetail.getUserAddress().getPhone());
            tvAddress.setText(orderDetail.getUserAddress().getProvince() + orderDetail.getUserAddress().getCity() + orderDetail.getUserAddress().getRegion() + orderDetail.getUserAddress().getAddressDetail());
            tvPrompt2.setText("· 商家同意后，请按照给出的退货地址退货，并请记录退货运单号\n· 如果商家拒绝，您的订单未得到处理，请联系商家协商处理");
        }
    }

    //请等待商家处理
    private void showWaiting() {
        if ("RETURN_MONEY_ONLY".equals(orderDetail.getAfterSaleApply().getType())) {
            setTitleText("申请售后");
        }
        tvOrderState.setText("请等待商家处理");
        if (TextUtils.equals(orderDetail.getAfterSaleApply().getType(), "RETURN_MONEY_PRODUCT")) {
            tvStatusText.setText("您已成功发起退款申请，请耐心等待商家处理。 " + SpannableStringUtils.getBuilder("商家同意退货后，请上传货品退回物流单号").setForegroundColor(getResources().getColor(R.color.color_CC1F1E)).create());
        } else {
            tvPrompt1.setText("· 如果商家拒绝，您的订单未得到处理，请联系商家协商处理");
        }
        tvPrompt1.setVisibility(View.VISIBLE);
        tvRevoke.setVisibility(View.VISIBLE);
        tvUpdate.setVisibility(View.VISIBLE);

    }
}
